from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List, Dict, Any
import uuid

from database import get_db
from model.models import ModelConfig

router = APIRouter(prefix="/api/model-config", tags=["Model Config"])

@router.get("", response_model=List[Dict[str, Any]])
def get_configs(db: Session = Depends(get_db)):
    configs = db.query(ModelConfig).order_by(ModelConfig.updated_at.desc()).all()
    return [c.to_dict() for c in configs]

@router.post("", response_model=Dict[str, Any])
def create_config(config: Dict[str, Any], db: Session = Depends(get_db)):
    if not config.get("api_key"):
        raise HTTPException(status_code=400, detail="API Key不能为空")
    if not config.get("base_url"):
        raise HTTPException(status_code=400, detail="Base URL不能为空")
    if not config.get("model"):
        raise HTTPException(status_code=400, detail="模型不能为空")
        
    new_config = ModelConfig(
        id=str(uuid.uuid4()),
        api_key=config.get("api_key"),
        base_url=config.get("base_url"),
        model=config.get("model"),
        remark=config.get("remark", ""),
        is_disabled=False
    )
    
    db.add(new_config)
    db.commit()
    db.refresh(new_config)
    return new_config.to_dict()

@router.put("/{config_id}", response_model=Dict[str, Any])
def update_config(config_id: str, config_data: Dict[str, Any], db: Session = Depends(get_db)):
    config = db.query(ModelConfig).filter(ModelConfig.id == config_id).first()
    if not config:
        raise HTTPException(status_code=404, detail="配置不存在")
        
    if "api_key" in config_data:
        config.api_key = config_data["api_key"]
    if "base_url" in config_data:
        config.base_url = config_data["base_url"]
    if "model" in config_data:
        config.model = config_data["model"]
    if "remark" in config_data:
        config.remark = config_data["remark"]
    if "is_disabled" in config_data:
        config.is_disabled = config_data["is_disabled"]
        
    db.commit()
    db.refresh(config)
    return config.to_dict()

@router.delete("/{config_id}")
def delete_config(config_id: str, db: Session = Depends(get_db)):
    config = db.query(ModelConfig).filter(ModelConfig.id == config_id).first()
    if not config:
        raise HTTPException(status_code=404, detail="配置不存在")
        
    db.delete(config)
    db.commit()
    return {"message": "删除成功"}
